/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SessionBeans.actions;

import entities.File;
import entities.Folder;
import java.util.List;

/**
 *
 * @author Tomas
 */
public class Utils {

    public static Folder findParentFolder(Folder root, String[] path) {
        return findFolder(root, path, true);
    }

    public static Folder findFolder(Folder root, String[] path) {
        return findFolder(root, path, false);
    }

    public static String getNameFromPath(String[] path) {
        return path[path.length - 1];
    }

    private static Folder findFolder(Folder root, String[] path, boolean parent) {
        Folder folderFind = root;
        int length = path.length;
        if (parent) {
            length -= 1;
        }
        if (length == 0) {
            return root;
        }
        for (int i = 0; i < length; i++) {
            List<Folder> folderList = folderFind.getFolderList();
            String folderName = path[i];
            for (Folder folder : folderList) {
                if (folder.getName().equalsIgnoreCase(folderName)) {
                    folderFind = folder;
                    if (i == length - 1) {
                        return folderFind;
                    }
                    break;
                }
            }
        }
        return null;
    }

    public static File findFile(Folder root, String[] path) {
        Folder findParentFolder = findParentFolder(root, path);
        if (findParentFolder.getFilesList() != null) {
            for (File file : findParentFolder.getFilesList()) {
                if (file.getFileName().equalsIgnoreCase(getNameFromPath(path))) {
                    return file;
                }
            }
        }
        return null;
    }
}
